package org.arch_learn.servlet_container.components.connector;

import org.arch_learn.servlet_container.components.Mapper;
import org.arch_learn.servlet_container.components.Service;
import org.arch_learn.servlet_container.components.connector.adapters.ServletRequestAdapter;
import org.arch_learn.servlet_container.components.connector.adapters.ServletResponseAdapter;
import org.arch_learn.servlet_container.pojo.CustomHttpServletRequest;
import org.arch_learn.servlet_container.pojo.CustomHttpServletResponse;
import org.arch_learn.servlet_container.pojo.Request;
import org.arch_learn.servlet_container.pojo.Response;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.io.InputStream;

public class Connector extends Thread {

    private Integer port;
    private Endpoint endpoint;
    private Service service;

    public Connector(Service service, Endpoint endpoint) {
        this.service = service;
        this.endpoint = endpoint;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public Endpoint getEndpoint() {
        return endpoint;
    }

    public void setEndpoint(Endpoint endpoint) {
        this.endpoint = endpoint;
    }

    public Service getService() {
        return service;
    }

    public void setService(Service service) {
        this.service = service;
    }

    @Override
    public void run() {
        try {
            //endPoint处理tcp/ip协议获取输入流
            InputStream inputStream = endpoint.read();
            //processor创建请求对象
            Request request = Processor.buildRequest(inputStream);
            //适配器将内部请求对象适配成servlet请求
            CustomHttpServletRequest httpServletRequest = ServletRequestAdapter.getHttpServletRequest(request);
            //mapper将servlet请求mapping到对应servlet
            HttpServlet servlet = Mapper.getMappedServlet(service, httpServletRequest);
            Response response = null;
            if (servlet != null) {
                //servlet处理请求
                CustomHttpServletResponse httpServletResponse = new CustomHttpServletResponse();
                servlet.service(httpServletRequest, httpServletResponse);
                response = ServletResponseAdapter.adaptHttpServletResponse(httpServletResponse);
                endpoint.write(response);
            } else {
                //无对应servlet先默认为静态资源
                System.out.println("---无合适的servlet处理请求url为" + httpServletRequest.getRequestURI() + "的请求---");
                response = ServletResponseAdapter.adaptStaticResourcesServletResponse(service, httpServletRequest);
                endpoint.writeStaticResources(response);
            }
            endpoint.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }
}
